import React, { useState, useEffect } from 'react';
import { Badge, Tooltip, Typography } from 'antd';
import { ClockCircleOutlined } from '@ant-design/icons';
import { useSessionManager } from '../hooks/useSessionManager';
import { useAuth } from '../hooks/useAuth';

const { Text } = Typography;

interface SessionStatusProps {
  showText?: boolean;
  style?: React.CSSProperties;
}

const SessionStatus: React.FC<SessionStatusProps> = ({ 
  showText = false, 
  style = {} 
}) => {
  const { isAuthenticated } = useAuth();
  const { getRemainingTime } = useSessionManager(isAuthenticated);
  const [remainingTime, setRemainingTime] = useState<number>(0);

  useEffect(() => {
    if (!isAuthenticated) {
      return;
    }

    // 更新剩余时间
    const updateRemainingTime = () => {
      const remaining = getRemainingTime();
      setRemainingTime(remaining);
    };

    // 立即更新一次
    updateRemainingTime();

    // 每分钟更新一次剩余时间
    const interval = setInterval(updateRemainingTime, 60000);

    return () => {
      clearInterval(interval);
    };
  }, [isAuthenticated, getRemainingTime]);

  // 如果用户未认证，不显示会话状态
  if (!isAuthenticated) {
    return null;
  }

  // 格式化剩余时间
  const formatTime = (milliseconds: number): string => {
    const minutes = Math.floor(milliseconds / (1000 * 60));
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;

    if (hours > 0) {
      return `${hours}小时${remainingMinutes}分钟`;
    } else {
      return `${remainingMinutes}分钟`;
    }
  };

  // 根据剩余时间确定状态颜色
  const getStatusColor = (milliseconds: number): string => {
    const minutes = Math.floor(milliseconds / (1000 * 60));
    if (minutes <= 5) {
      return 'red'; // 5分钟内显示红色
    } else if (minutes <= 10) {
      return 'orange'; // 10分钟内显示橙色
    } else {
      return 'green'; // 其他情况显示绿色
    }
  };

  const statusColor = getStatusColor(remainingTime);
  const formattedTime = formatTime(remainingTime);
  const tooltipTitle = `会话将在 ${formattedTime} 后超时`;

  if (showText) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', ...style }}>
        <ClockCircleOutlined style={{ color: statusColor, marginRight: 4 }} />
        <Text style={{ color: statusColor, fontSize: '12px' }}>
          {formattedTime}
        </Text>
      </div>
    );
  }

  return (
    <Tooltip title={tooltipTitle} placement="bottom">
      <Badge 
        color={statusColor} 
        style={{ cursor: 'pointer', ...style }}
      >
        <ClockCircleOutlined style={{ color: statusColor }} />
      </Badge>
    </Tooltip>
  );
};

export default SessionStatus;